<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
<!--  导航区    -->
      <div>
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-menu-item index="0" @click="handleMenuItemClick(undefined)">全部</el-menu-item>
          <el-menu-item index="1" @click="handleMenuItemClick(1)">已呼叫</el-menu-item>
          <el-menu-item index="2" @click="handleMenuItemClick(0)">未呼叫</el-menu-item>
        </el-menu>
      </div>
<!-- 资源列表卡片区 -->
      <el-form :inline="true" ref="form"  size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              placeholder="请选择账号"
              v-model="queryMap.accountName"
              @change="handleChange"
              filterable

          >
            <el-option label="全部" value=""></el-option>
            <el-option
                v-for="(name) in accountName"
                :key="name"
                :label="name"
                :value="name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 140px;"
              clearable
              v-model="queryMap.resourceName"
              placeholder="请输入客户名称"

          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 120px;"
              placeholder="请选择标签"
              v-model="queryMap.resourceTag"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="未标记" value="0"></el-option>
            <el-option label="无效" value="1"></el-option>
            <el-option label="待定" value="2"></el-option>
            <el-option label="有效" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item >
          <el-input
              style="width: 150px;"
              clearable
              placeholder="请输入联系人名称"
              v-model="queryMap.linkman"
          ></el-input>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 130px;"
              clearable
              placeholder="请输入电话"
              v-model="queryMap.phoneA"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              placeholder="请选择行业类别"
              v-model="queryMap.industryId"
          >
            <el-option label="全部" value=""></el-option>
            <el-option v-for="dept in IndustryVOs" :label="dept.options" :value="dept.industryId">

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryMap.userId" style="width: 140px;" filterable placeholder="请选择归属人">
            <el-option label="全部" value=" "></el-option>
            <el-option
                v-for="item in options_user"
                :key="item.userId"
                :label="item.userName+'('+item.nickName+')'"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              placeholder="是否存在"
              v-model="queryMap.isExists"
          >
            <el-option label="全部" value=" "></el-option>
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 140px;"
              clearable
              v-model="queryMap.taskPackageName"
              placeholder="请输入任务名称"

          ></el-input>
        </el-form-item>
        <el-form-item label="时间筛选:">
          <el-select
              style="width: 120px;"
              v-model="queryMap.time"
              placeholder="请选择时间"
          >
            <el-option label="创建时间" value="1"></el-option>
            <el-option label="呼叫时间" value="2"></el-option>
            <el-option label="更新时间" value="3"></el-option>
          </el-select>
          <el-date-picker
              v-model="value2"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              :clearable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item >
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" @click="searchResource" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button v-hasPermission="'resource:insertHigh_seas'" @click="batchTransferToOpenSea" style="" icon="el-icon-position">批量转公海</el-button>
        <el-button v-hasPermission="'resource:export'" @click="batchExportExcel" style="" icon="el-icon-download">批量导出</el-button>
      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable" :data="testData"  size="small"  @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">

        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="accountName" label="归属账号" width="150"></el-table-column>
        <el-table-column prop="taskPackageName" label="任务名称" width="150"></el-table-column>
        <el-table-column prop="resourceName" label="客户名称" width="100"></el-table-column>
        <el-table-column prop="phoneA" label="电话A" width="100" >
<!--          <template v-slot="scope">-->
<!--            <span>{{scope.row.phoneA}}</span>-->
<!--            <el-tooltip content="外呼" placement="top" effect="light">-->
<!--              <el-button-->
<!--                  v-hasPermission="'resource:callResource'"-->
<!--                  icon="el-icon-phone"-->
<!--                  @click="callResource(scope.row.phoneA)"-->
<!--                  style="margin-left: 20px;"-->
<!--                  plain-->
<!--                  circle-->
<!--              ></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column prop="phoneB" label="电话B" width="100">
<!--          <template v-slot="scope">-->
<!--            <span>{{scope.row.phoneB}}</span>-->
<!--            <el-tooltip content="外呼" v-if="scope.row.phoneB && scope.row.phoneB!== ''" placement="top" effect="light">-->
<!--              <el-button-->
<!--                  v-hasPermission="'resource:callResource'"-->
<!--                  icon="el-icon-phone"-->
<!--                  @click="callResource(scope.row.phoneB)"-->
<!--                  style="margin-left: 20px;"-->
<!--                  plain-->
<!--                  circle-->
<!--              ></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column prop="isCall" label="是否呼叫" width="100">
          <template v-slot="scope">
            <span>{{showCall(scope.row)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="resourceTag" label="资源标签" width="100">
          <template v-slot="scope">
            <span>{{showTag(scope.row)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="归属人" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="linkman" label="联系人姓名" width="100"></el-table-column>
        <el-table-column prop="isExists" label="是否存在" width="100">
          <template v-slot="scope">
            <span>{{showExists(scope.row)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="industryOptions" label="行业类型" width="100"></el-table-column>
        <el-table-column prop="remark" label="备注" width="250"></el-table-column>
        <el-table-column label="操作" fixed="right" width="420">
          <template v-slot="scope">
<!--            <el-tooltip content="外呼" placement="top" effect="light">-->
<!--              <el-button v-hasPermission="'resource:callResource'" icon="el-icon-phone" @click="callResource(scope.row.phoneA)" plain circle ></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="复制微信号" placement="top" effect="light">
              <el-button icon="el-icon-document-copy" plain circle @click="copyPhoneA(scope.row.phoneA)"></el-button>
            </el-tooltip>
            <el-button type="primary" plain size="mini"  @click="openDrawer(scope.row)">详情</el-button>
            <el-button type="danger"  size="mini" @click="addToBlacklist(scope.row.resourceName, scope.row.phoneA,scope.row.phoneB,scope.row.accountName)">加入黑名单</el-button>
            <el-button type="warning" v-hasPermission="'resource:insertHigh_seas'"  size="mini" @click="insertHigh_seas_clientList(scope.row.resourceId)">转公海</el-button>
            <el-tooltip content="标签" placement="top" effect="light">
              <el-button type="primary"  @click="openLabel(scope.row.resourceId)" size="small" icon="el-icon-circle-plus-outline" plain circle ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" v-hasPermission="'resource:delete'"  @click="deleteResourceInfoById(scope.row.resourceId)" size="small" icon="el-icon-delete" plain circle ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="[6, 10, 20, 30,50,100,300,500]"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

      <!-- 添加标签弹出层 -->
      <div v-if="isVisible" class="popups" @click.self="isVisible=false">
        <el-main style="width: 500px; height: 230px; margin: 10vh auto;">
          <div class="header">
            <h3 style="flex: 1">标记标签</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle  @click="isVisible=false"></el-button>
            </el-tooltip>
          </div>
          <div>
            <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh">
              <el-form-item >
              <el-select
                  clearable
                  style="width: 350px;"
                  placeholder="请选择标签"
                  v-model="updataResourceInfo.labelId"
              >
                <el-option v-for="dept in labelInfoList" :label="dept.labelName" :value="dept.labelId"></el-option>
              </el-select>
              </el-form-item>
              <el-form-item >
                <el-button v-hasPermission="'resource:updateResource'" type="primary" @click="updateResource" icon="el-icon-search">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </div>

      <!-- 详情抽屉 -->
      <el-drawer

          title="更新资源信息"
          :visible.sync="drawer"
          direction="rtl"
          size="50%"
          >
    <el-card style="margin: 0 3vh">
    <el-form :rules="formRules" :model="updataResourceInfo"  :inline="true" ref="updataResourceInfo"  style="padding: 2vh 3vh" >
      
          <el-form-item prop="resourceName" label="客户名称" style="margin-left: 2.9vh">
            <el-input
                v-model="updataResourceInfo.resourceName"
            style="width: 500px;"
            maxlength="60"
            show-word-limit
            ></el-input>
            <span style="color:red;"> *</span>
          </el-form-item>
      <el-form-item prop="linkman" label="联系人姓名" style="margin-left: 1.2vh">
        <el-input

            v-model="updataResourceInfo.linkman"
            style="width: 250px"
        ></el-input>
        <span style="color:red;"> *</span>
      </el-form-item>
      <el-form-item label="行业类别" style="margin-left: 5.2vh">
        <el-select
            clearable
            style="width: 140px;"
            placeholder="请选择"
            v-model="updataResourceInfo.industryId"
        >
          <el-option v-for="dept in updateIndustryVOs" :label="dept.options" :value="dept.industryId">
          </el-option>
        </el-select>
        <el-button class="el-icon-s-cooperation dataDict" style="left: 16vh;"></el-button>
      </el-form-item>
      <el-form-item prop="phoneA" label="联系人电话A" style="">
        <el-input

            v-model="updataResourceInfo.phoneA"
            style="width: 180px"
            show-word-limit
        ></el-input>
        <span style="color:red;"> *</span>
      </el-form-item>
      <el-form-item prop="phoneB" label="联系人电话B" style="margin-left: 3.5vh">
        <el-input

            v-model="updataResourceInfo.phoneB"
            style="width: 180px"
            show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="客户种类" style="margin-left: 3vh">
        <el-select
            clearable
            style="width: 140px;"
            placeholder="请选择"
            v-model="updataResourceInfo.clientTypeId"
        >
          <el-option v-for="dept in clienttypeList" :label="dept.options" :value="dept.clientTypeId">
          </el-option>
        </el-select>
        <el-button class="el-icon-s-cooperation dataDict" style="left: 18.5vh;"></el-button>
      </el-form-item>
      <el-form-item label="资源标签" style="margin-left: 6vh">

        <el-radio-group v-model="updataResourceInfo.resourceTag" size="mini">
          <el-radio-button :label="0" value="0">未标记</el-radio-button>
          <el-radio-button :label="1" value="1" >无效</el-radio-button>
          <el-radio-button :label="2" value="2">待定</el-radio-button>
          <el-radio-button :label="3" value="3">有效</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" style="margin-left: 6.5vh">
        <el-input
            type="textarea"
            placeholder="请输入内容"
            style="width: 63.3vh"
            maxlength="150"
            show-word-limit
            v-model="updataResourceInfo.remark"
        >
        </el-input>
      </el-form-item>
      <el-form-item style="margin: 2vh 0 0 66vh">
        <el-button v-hasPermission="'resource:updateResource'" type="primary" size="medium" @click="updateResource">保存</el-button>
      </el-form-item>
        </el-form>
    </el-card>

      </el-drawer>
    </el-card>
    <!-- 加入黑名单备注弹出层 -->
    <div v-if="addBlacklistPopupVisible" class="popups" @click.self="addBlacklistPopupVisible=false">
      <el-main style="width: 500px; height: 300px; margin: 10vh auto;">
        <div class="header">
          <h3 style="flex: 1">加入黑名单</h3>
          <el-tooltip content="关闭页面" placement="top" effect="light">
            <el-button icon="el-icon-circle-close" circle @click="addBlacklistPopupVisible=false"></el-button>
          </el-tooltip>
        </div>
        <el-form :inline="true" ref="blacklistForm" :model="blacklistFormData" size="small" style="margin-top: 2vh">
          <el-form-item>
            <el-select
                clearable
                style="width: 140px;"
                placeholder="请选择账号"
                v-model="blackListaccountName"
                filterable
            >
              <el-option
                  v-for="(name) in accountName"
                  :key="name"
                  :label="name"
                  :value="name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择号码">
            <el-checkbox v-model="isPhoneASelected">{{ blacklistPhoneA }}</el-checkbox>
            <el-checkbox v-if="blacklistPhoneB" v-model="isPhoneBSelected">{{ blacklistPhoneB }}</el-checkbox>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
                v-model="blacklistFormData.remark"
                style="width: 300px"
                maxlength="150"
                show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-top: 2vh">
            <el-button v-hasPermission="'resource:insertBlackList'" type="primary" @click="confirmAddToBlacklist(isPhoneASelected,isPhoneBSelected)">确认</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </div>
  </div>

</template>
<script>
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";
export default {
  components: { ElectUsersBox },
  data() {
    return {
      isVisible: false, //添加标签弹出层是否展示
      radio: "未标记", //抽屉中资源标签选项
      drawer: false, //抽屉是否显示
      activeIndex: "0", //初始显示菜单下标
      total: 0,
      blackListaccountName:"",
      multipleSelection: [],
      testData: [], // 修改为初始空数组
      extractedData: [], //下拉框
      initialExtractedData: [], //下拉框的备份
      IndustryVOs:[],
      updateIndustryVOs:[],
      clienttypeList:[],
      value2:"",
      updataResourceInfo:[],
      options_user:[],
      accountName:[],
      blackListChange:[],
      addBlacklistPopupVisible: false, // 加入黑名单备注弹出层是否显示
      labelInfoList:[],
      isPhoneASelected:false,
      isPhoneBSelected:false,
      blacklistFormData: {
        accountName:'',
        remark: '' // 加入黑名单的备注
      },
      appId: "",
      callerNbr: "",
      calleeNbr: "",
      bindNbr: "",
      notifyUrl:"http://47.99.186.44:8989/comcentre/call/callBackSaveLog",//回拨接口ip：port 换成上线的服务器
      sign: "",
      formRules: {
        resourceName: [
          {required: true, message: '客户名称不能为空！', trigger: 'blur'}
        ],
        linkman: [
          {required: true, message: '联系人不能为空！', trigger: 'blur'}
        ],
        phoneA: [
          {required: true, message: '电话A不能为空！', trigger: 'blur'},
          {
            pattern: /^(?:\+86|0086)?\s*-?\s*(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-\d{7,8})|(?:0\d{10}))$/,
            message: '请输入有效的手机号码',
            trigger: 'blur'
          }
        ],
        phoneB: [
          {required: false, message: '如需填写，请填写有效的电话B！', trigger: 'blur'},
          {
            pattern: /^(?:\+86|0086)?\s*-?\s*(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-\d{7,8})|(?:0\d{10}))$/,
            message: '如需填写，请输入有效的手机号码',
            trigger: 'blur'
          }
        ],
      },

      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 6,
        //获取任务包名称
        resourceName: "",
        accountName:"",
        resourceId:"",
        taskPackageName: "",
        resourceTag: "",
        linkman: "",
        phoneA:"",
        isExists: "",
        userId: "",
        isCall: "",
        time:"1",
        labelId:"",
        startTime:"",
        endTime:"",
        industryId:"",
      },
      updateForm: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ],
      },
      durationOptions: {
        0: "1秒",
        1: "20秒",
        2: "30秒",
        3: "40秒",
        4: "50秒",
        5: "60秒",
        6: "70秒",
        7: "80秒",
        8: "90秒",
        9: "100秒",
        10: "110秒",
        11: "120秒",
        12: "120秒以上"
      },
      loading: false // 添加loading初始定义
    };
  },
  methods: {


    /**
     * 导航栏点击方法
     * @param key 点击下标
     */
    handleSelect(key) {},
    /**
     * 加载资源列表
     */
    async getResourceList() {
      this.loading = true;
      try {
        const res = await this.$http.get("/resourceInfo/findResourceInfo", {
          params: this.queryMap
        });
        if (!res.data.success) {
          return this.$message.error("获取资源列表失败:" + res.data.data.errorMsg);
        }
        this.total = res.data.data.total;
        this.testData = res.data.data.rows;
      } catch (error) {
        console.error("获取资源列表时出错", error);
      }
    },
    handleChange() {
      this.getAllIndustryList();
      this.selectUser();
      this.queryMap.industryId='';
      this.queryMap.userId='';
    },


    /**
     * 加载行业类型列表
     */
    async getAllIndustryList() {
      this.loading = true;

      try {
        const { data: res } = await this.$http.get("/resourceInfo/findIndustryVOList", {
          params: {accountName:this.queryMap.accountName}
        });
        let validData = [];
        if (Array.isArray(res)) {
          validData = res;
        } else if (typeof res === 'object' && res.success) {
          validData = res.data || [];
          console.log("aaaaaa"+validData)
        }
        if (Array.isArray(validData)) {
          this.IndustryVOs = validData.map(item => ({
            industryId: item.industryId,
            options: item.options
          }));
        }
      } catch (error) {
        // 处理其他异常
        console.error('获取行业类型列表时遇到异常', error);
        this.$message.error('获取行业类型列表时遇到异常');
      }
    },
    // 加载行业类型列表（更新时使用）
    async getAllIndustryListInUpdate(accountName) {
      this.loading = true;
      try {
        const { data: res } = await this.$http.get("/resourceInfo/findIndustryVOList", {
          params: { accountName: accountName }
        });
        let validData = [];
        if (Array.isArray(res)) {
          validData = res;
        } else if (typeof res === 'object' && res.success) {
          validData = res.data || [];
          console.log("aaaaaa" + validData);
        }
        if (Array.isArray(validData)) {
          this.updateIndustryVOs = validData.map(item => ({
            industryId: item.industryId,
            options: item.options
          }));
        }
      } catch (error) {
        console.error('获取行业类型列表时遇到异常', error);
        this.$message.error('获取行业类型列表时遇到异常');
      }
    },
    /**
     * 加载客户类型列表
     */
    async findClienttypeList(accountName) {
      this.loading = true;
      try {
        const { data: res } = await this.$http.get("/resourceInfo/findClienttypeList",{
          params: { accountName: accountName }
        });
        console.log('获取客户类型列表响应数据:', res);
        let validData = [];
        if (Array.isArray(res)) {
          validData = res;
        } else if (typeof res === 'object' && res.success) {
          validData = res.data || [];
        }
        if (Array.isArray(validData)) {
          this.clienttypeList = validData.map(item => ({
            clientTypeId: item.clientTypeId,
            options: item.options
          }));
        }
      } catch (error) {
        // 处理其他异常
        console.error('获取客户类型列表时遇到异常', error);
        this.$message.error('获取客户类型列表时遇到异常');
      }
    },
    /**
     * 获得账号信息
     */
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data.errorMsg);
      }
      this.accountName = res.data

    },

    /**
     * 加载标签列表
     */
    async findLabelInfoList() {
      this.loading = true;
      try {
        const { data: res } = await this.$http.get("/resourceInfo/findLabelInfoList", {
          accountName:this.queryMap.accountName
        });
        console.log('获取标签列表响应数据:', res);
        let validData = [];
        if (Array.isArray(res)) {
          validData = res;
        } else if (typeof res === 'object' && res.success) {
          validData = res.data || [];
        }
        if (Array.isArray(validData)) {
          this.labelInfoList = validData.map(item => ({
            labelId: item.labelId,
            labelName: item.options
          }));
        }
      } catch (error) {
        // 处理其他异常
        console.error('获取标签列表时遇到异常', error);
        this.$message.error('获取标签列表时遇到异常');
      }
    },

    /**
     * 加载归属人列表
     */
    async selectUser() {
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/", {
        accountName:this.queryMap.accountName
      });
      if (res.success) {
        this.options_user = res.data;
        console.log("归属人信息"+options_user)
      } else {
        return this.$message.error("系统通知信息编辑失败:" + res.message);
      }
    },

    //打开详情抽屉
    openDrawer(row) {
      if (typeof row.resourceId === 'undefined') {
        console.error('id is undefined when opening drawer');
        return;
      }
      this.drawer = true;
      this.queryMap.resourceId = row.resourceId;
      this.findResourceListById(row.resourceId).then(() => {
        this.getAllIndustryListInUpdate(row.accountName);
        this.findClienttypeList(row.accountName);
      });
    },

    openLabel(id){
      if (typeof id === 'undefined') {
        console.error('id is undefined when opening drawer');
        return;
      }
      this.isVisible = true;
      this.queryMap.resourceId = id;
      this.findResourceListById(id);
    },
    /**
     * 根据id获取资源列表
     * @param id 资源id
     */
    async findResourceListById(id) {
      try {
        const res = await this.$http.get("/resourceInfo/findResourceListById", {
          params: { id: id }
        });
        if (!res ||!res.data ||!Array.isArray(res.data)) {
          return this.$message.error("获取资源详情失败，数据格式异常");
        }
        this.updataResourceInfo = res.data[0] || [];
        console.log(this.updataResourceInfo);
      } catch (error) {
        if (error.response) {
          this.$message.error(`请求失败，状态码: ${error.response.status}`);
        } else if (error.request) {
          this.$message.error('请求发出，但未收到响应');
        } else {
          this.$message.error('请求过程中发生错误');
        }
        console.error("获取资源详情时出错", error);
      }
    },
    //删除资源
    async deleteResourceInfoById(id){
      this.loading = true;
      const confirm = await this.$confirm(
          "此操作将把该资源删除到回收站, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除操作"
        });
      });
      if(confirm === "confirm") {
        try {
          const res = await this.$http.get('/resourceInfo/deleteResourceInfoById', {
            params: {
              id: id
            }
          });
          // 假设后端返回1表示成功，其他值表示失败
          if (res.data === 1) {
            this.$message.success('资源删除成功');
            // 重新获取资源列表，以显示更新后的数据
            await this.getResourceList();
          } else {
            this.$message.error('资源删除失败');
          }
        } catch (error) {
          console.error('删除资源信息时出错', error);
          this.$message.error('删除资源信息时遇到异常，请检查网络或联系管理员');
        } finally {
          this.loading = false;
        }
      }
    },
    //修改资源
    async updateResource() {
      // 简单校验，确保updataResourceInfo中有数据
      if (!this.updataResourceInfo || Object.keys(this.updataResourceInfo).length === 0) {
        return this.$message.error('没有可更新的资源信息');
      }
      // 检查是否有id
      if (!('resourceId' in this.updataResourceInfo)) {
        return this.$message.error('资源id缺失，无法更新');
      }
      // 输出要修改的数据
      console.log('即将更新的资源数据:', this.updataResourceInfo);
      this.loading = true;
      const valid = await this.$refs.updataResourceInfo.validate();
      if (valid) {
        try {
          const res = await this.$http.post('/resourceInfo/updateResourceListById', this.updataResourceInfo);
          if (res.data.success) {
            // 假设后端返回的res.data.data是更新后的资源对象
            const {id} = res.data.data;
            this.$message.success('资源信息更新成功');
            // 关闭抽屉
            this.drawer = false;
            this.isVisible = false;
            // 重新获取资源列表，以显示更新后的数据
            await this.getResourceList();
            return {id};
          } else {
            // 检查res.data.data是否存在
            if (!res.data.data){
              this.$message.warning("电话号码已存在")
            }
            if ( 'errorMsg' in res.data.data) {
              this.$message.error('资源信息更新失败:' + res.data.data.errorMsg);
            } else {
              this.$message.error('电话号码已存在');
            }
            return null;
          }
        } catch (error) {
          console.error('更新资源信息时出错', error);
          this.$message.warning('号码已存在');
          return null;
        } finally {
          this.loading = false;
        }
      }
    },
    //加入黑名单
    async addToBlacklist(resourceName, phoneA,phoneB,accountName) {
      this.blacklistResourceName = resourceName;
      this.blacklistPhoneA = phoneA;
      this.blacklistPhoneB = phoneB;
      this.blackListaccountName = accountName;


      if (phoneB) {
        this.isPhoneASelected = true;
        this.isPhoneBSelected = true;
      }else{
        this.isPhoneASelected = true;
        this.isPhoneBSelected = false;
      }

      this.addBlacklistPopupVisible = true;


    },
    //加入黑名单
    async confirmAddToBlacklist(isPhoneASelected,isPhoneBSelected) {
      this.loading = true;
      try {

        // 检查是否至少选中一个电话号码
        if (!this.isPhoneASelected && (!this.blacklistPhoneB || !this.isPhoneBSelected)) {
          this.$message.warning('请至少选择一个电话号码加入黑名单');
          this.loading = false;
          return;
        }
        // 根据选择状态决定电话号码的值
        let phoneAValue = '';
        let phoneBValue = '';

        if (isPhoneASelected) {
          phoneAValue = this.blacklistPhoneA;
        }

        if (isPhoneBSelected) {
          phoneBValue = this.blacklistPhoneB;
        }

        const resourceInfoVO = {
          resourceName: this.blacklistResourceName,
          phoneA: phoneAValue,
          phoneB: phoneBValue,
          remark: this.blacklistFormData.remark
        };
        console.log("加入黑名单的值"+resourceInfoVO)
        const response = await this.$http.post('/resourceInfo/insertBlackList', resourceInfoVO);
        if (response.data > 0) {
          this.$message.success('加入黑名单成功');
          // 重新获取资源列表，以显示更新后的数据
          await this.getResourceList();
        } else {
          this.$message.error('该资源已存在黑名单');
        }
      } catch (error) {
        console.error('加入黑名单时出错', error);
        this.$message.error('加入黑名单时遇到异常，请检查网络或联系管理员');
      } finally {
        this.loading = false;
        this.addBlacklistPopupVisible = false;
        this.blacklistFormData.remark = '';
      }
    },
    //外呼
    async callResource(PhoneA) {
     this.calleeNbr = PhoneA;
     await this.outPhone();
    },
    //转入公海
    async insertHigh_seas_clientList(id) {
      try {
        // 确认弹窗
        const confirm = await this.$confirm(
            "此操作将把该资源转入公海, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消转入公海操作"
          });
        });
        if (confirm) {
          // 发送请求
          const response = await this.$http.post("/highSeasClient/toHighSeas", {
            id:[id]
          });
          // 检查响应结果
          if (response.data.data > 0) {
            this.$message.success('加入公海成功');
            // 重新获取资源列表，以显示更新后的数据
            await this.getResourceList();
          } else {
            this.$message.error(response.data.message || '加入公海失败');
          }
        }
      } catch (error) {
        // 处理异常
        if (error.response) {
          // 后端返回的错误
          this.$message.error(`加入公海失败：${error.response.data.message || '未知错误'}`);
        } else if (error.request) {
          // 请求未收到响应（网络错误）
          this.$message.error('网络错误，请检查网络连接');
        } else {
          // 其他错误
          console.error('加入公海时出错', error);
          this.$message.error('加入公海时遇到异常，请检查网络或联系管理员');
        }
      }
    },
    //批量转入公海
    async batchTransferToOpenSea() {
      // 检查是否选中了记录
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请至少选择一条记录');
      }
      try {
        // 确认弹窗
        const confirm = await this.$confirm(
            "此操作将把选中的资源转入公海, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消转入公海操作"
          });
          return false; // 用户取消操作
        });
        if (confirm) {
          // 提取资源 ID
          const resourceIds = this.multipleSelection.map(row => row.resourceId);
          // 发送批量请求
          const response = await this.$http.post("/highSeasClient/toHighSeas", {
            id: resourceIds
          });
          // 处理响应结果
          if (response.data.data > 0) {
            const successCount = response.data.data; // 获取成功处理的记录数
            if (successCount === this.multipleSelection.length) {
              this.$message.success(`全部 ${successCount} 条记录成功转入公海`);
            } else if (successCount > 0) {
              this.$message.warning(
                  `${successCount} 条记录成功转入公海，${this.multipleSelection.length - successCount} 条记录失败`
              );
            } else {
              this.$message.error('批量转入公海失败');
            }
            // 重新获取资源列表
            await this.getResourceList();
          } else {
            this.$message.error(response.data.message || '批量转入公海失败');
          }
        }
      } catch (error) {
        // 处理异常
        if (error.response) {
          this.$message.error(`批量转入公海失败：${error.response.data.message || '未知错误'}`);
        } else if (error.request) {
          this.$message.error('网络错误，请检查网络连接');
        } else {
          console.error('批量转入公海时出错', error);
          this.$message.error('批量转入公海时遇到异常，请检查网络或联系管理员');
        }
      }
    },
    //复制电话号码A
    copyPhoneA(phoneA) {
      const textarea = document.createElement('textarea');
      textarea.value = phoneA;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('微信号复制成功');
        } else {
          this.$message.error('微信号复制失败');
        }
      } catch (err) {
        this.$message.error('微信号复制失败');
      }
      document.body.removeChild(textarea);
    },
    /**
     * 搜索系统通知
     */
    async searchResource() {
      this.getTime();
      await this.getResourceList();

    },
    /**
     * 重置
     */
    reset() {
      this.queryMap = {
        pageNum: 1,
        pageSize: 6,
        //获取任务包名称
        resourceName: "",
        taskPackageName: "",
        resourceTag: "",
        linkman: "",
        time:'1',
        phoneA:"",
        isExists: "",
        userName: "",
        isCall: ""
      };
      this.defaultTime();
    },
    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (this.$refs.multipleTable) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("******************************", val);
    },
    async batchExportExcel() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请至少选择一条记录');
      }
      const resourceIds = this.multipleSelection.map(row => row.resourceId);
      try {
        const res = await axios.request({
          url: 'http://47.99.186.44:8989/resourceInfo/excelBatch',
          method: 'post',
          responseType: 'blob',
          headers: { 'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN) },
          // 直接发送resourceIds数组
          data: resourceIds
        });
        if (res.headers["content-type"] === "application/json") {
          return this.$message.error(
              "Subject does not have permission [user:export]"
          );
        }
        const data = res.data;
        let url = window.URL.createObjectURL(data);
        const a = document.createElement("a");
        document.body.appendChild(a);
        a.href = url;
        a.download = "批量导出资源列表.xls";
        a.click();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('批量导出时出错', error);
        this.$message.error('批量导出时遇到异常，请检查网络或联系管理员');
      }
    },
    /**
     * 显示是否呼叫
     */
    showCall(row, column) {
      let call='';
      if(row.isCall==0){
        call = '未呼叫';
      }else if(row.isCall==1) {
        call = '已呼叫';
      }else{
        call = '未呼叫';
      }
      return call;
    },
    /**
     * 显示资源标签
     */
    showTag(row, column) {
      let tag='';
      if(row.resourceTag==0){
        tag = '未标记';
      }else if(row.resourceTag==1) {
        tag = '无效';
      }else if(row.resourceTag==2) {
        tag = '待定';
      }else if(row.resourceTag==3) {
        tag = '有效';
      }else{
        tag = '未标记';
      }
      return tag;
    },
    showExists(row, column){
      let value='';
      if(row.isExists==0){
        value = '不存在';
      }else if(row.isExists==1) {
        value = '已存在';
      }else{
        value = '不存在';
      }
      return value;
    },
    //头部选择栏
    handleMenuItemClick(value) {
      // 在这里你可以根据queryMap.isCall的值执行相应的业务逻辑
      if (value === undefined) {
        this.queryMap.resourceTag = undefined;
        this.queryMap.isCall = value;
        // 全部选项的逻辑
        console.log('全部选项被点击');
      } else if (value === 1) {
        this.queryMap.resourceTag = undefined;
        this.queryMap.isCall = value;
        // 已呼叫选项的逻辑
        console.log('已呼叫选项被点击');
      } else if (value === 0) {
        this.queryMap.resourceTag = undefined;
        this.queryMap.isCall = value;
        // 未呼叫选项的逻辑
        console.log('未呼叫选项被点击');
      }else if (value ===2){
        this.queryMap.isCall = undefined;
        this.$set(this.queryMap,'resourceTag', '3');
      }
      this.searchResource();
    },
    /**
     * 通用的查询方法
     */
    performQuery() {
      this.getResourceList();

    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.performQuery();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.performQuery();
    },
    getTime() {
      if (this.value2 != null && this.value2.length === 2) {
        console.log("时间：", this.value2);
        // 格式化开始和结束时间
        this.queryMap.startTime = this.formatDate(this.value2[0], false); // 开始日期
        this.queryMap.endTime = this.formatDate(this.value2[1], true);    // 结束日期
      } else {
        this.queryMap.startTime = "";
        this.queryMap.endTime = "";
      }
    },
    //默认时间
    defaultTime() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
      end.setTime(end.getTime());
      this.value2 = [start, end]; // 重置为两天
      this.getTime()
    },
    //定义一个格式化时间的函数（格式为 yyyy-MM-dd）
    formatDate(date, isEnd) {
      if (date != null) {
        let formattedDate = new Date(date); // 复制一份新的日期对象，避免修改原始日期
        if (isEnd) {
          // 对结束时间加一天，以确保区间包括结束日期当天
          formattedDate.setDate(formattedDate.getDate() + 1);
        }
        const year = formattedDate.getFullYear();
        const month = ('0' + (formattedDate.getMonth() + 1)).slice(-2);
        const day = ('0' + formattedDate.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
      }
      return null;
    },
    // async outPhone() {
    //   if (this.appId==null||this.appId==""){
    //     return this.$message.error("账户信息错误：应用key");
    //   }
    //   if (this.callerNbr==null||this.callerNbr==""){
    //     return this.$message.error("账户信息错误：手机号");
    //   }
    //   if (this.calleeNbr==null||this.calleeNbr==""){
    //     return this.$message.error("外呼号码不可为空");
    //   }
    //   if (this.bindNbr==null||this.bindNbr==""){
    //     return this.$message.error("账户信息错误：中间号");
    //   }
    //   let ifOpen=await this.getSign();
    //   if (ifOpen==false){
    //     return;
    //   }
    //   if (this.sign==null||this.sign==""){
    //     return this.$message.error("签名失败");
    //   }
    //   await this.ready();
    // },
    // async ready() {
    //   axios.post("https://yx.jsyouxiao.com/apis/public/apiCall/call", {
    //     "appId": this.appId,
    //     "callerNbr": this.callerNbr,
    //     "calleeNbr": this.calleeNbr,
    //     "notifyUrl":this.notifyUrl,
    //     "bindNbr": this.bindNbr,
    //     "sign": this.sign,
    //   }).then(async res => {
    //     if (res != null) {
    //       if (res.data.code == '200') {
    //         console.log(res.data);
    //         let sessionId = res.data.data.sessionId;
    //         if (sessionId != null) {
    //           const { data: res2 } = await this.$http.post("/comcentre/call/saveLog", {
    //             sessionId: sessionId,
    //             bindNbr: this.bindNbr,
    //             callerNbr: this.callerNbr,
    //             calleeNbr: this.calleeNbr
    //           });
    //           console.log(res2);
    //           if (!res2.success) {
    //             console.log(res.data);
    //             return this.$message.error(res2.data.msg);
    //           }
    //         }
    //         return this.$message.info(res.data.msg);
    //       } else if (res.data.code == '500') {
    //         return this.$message.error(res.data.msg);
    //       }
    //     }
    //   });
    // },
    // async getSign(){
    //   const {data:res} = await this.$http.post("/comcentre/call/getSign",{
    //     appId:this.appId,
    //     callerNbr:this.callerNbr,
    //     calleeNbr:this.calleeNbr,
    //     notifyUrl:this.notifyUrl,//回拨接口ip：port 换成上线的服务器
    //     bindNbr:this.bindNbr
    //   })
    //   if (!res.success){
    //     this.$message.error("错误信息:"+res.data);
    //     return false;
    //   }
    //   this.sign=res.data;
    // },
    // async getCallerNbr() {
    //   const { data: res } = await this.$http.get("/comcentre/call/getCallerNbr");
    //   if (res != null) {
    //     this.callerNbr = res.data;
    //   }
    // },
    // async getBindNbr() {
    //   const { data: res } = await this.$http.get("/comcentre/call/getBindNbr");
    //   if (res != null) {
    //     this.bindNbr = res.data;
    //   }
    // },
    // async getAppId() {
    //   const { data: res } = await this.$http.get("/comcentre/call/getAppId");
    //   if (res != null) {
    //     this.appId = res.data;
    //   }
    // }
  },
  created() {
    this.defaultTime();
    this.searchResource();
    this.getAllIndustryList();
    // this.findClienttypeList();
    this.findLabelInfoList();
    this.selectUser();
    // this.getCallerNbr();
    // this.getBindNbr();
    // this.getAppId();
    this.getAccountNameList();
  },
};
</script>

<style scoped>
.hint{
  margin-left: 2vh;font-weight: 400;font-size: 12px;color: red;
}

.dataDict{
  border: none;
  background-color: #fff;
  position: absolute;
  padding: .6vh 0;
  font-size: 18px;
}
.popups{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}
.popups .el-main{
  background-color: #fff;
  margin: 15vh auto;
}
.popups .el-main .header{
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;

}
.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}
</style>